import http from '@ohos.net.http'
import router from '@ohos.router'
import promptAction from '@ohos.promptAction'
import { LoginResult } from '../types/member'
import { Data } from '../types/Comm'

const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'

export const ht1 = <T>(url: string, options?: http.HttpRequestOptions) : Promise<Data<T>> => {
  if (!url.startsWith('http')) {
    url = baseURL + url
  }

  options.header = {
    ...options.header,
    'source-client': "miniapp"
  }

  let memberStore: LoginResult = AppStorage.Get("memberStore")
  const token = memberStore?.token
  if (token) {
    options.header = {
      ...options.header,
      'Authorization': token
    }
  }

  promptAction.showToast({
    message: url,
    duration: 6000
  })

  console.log("请求头信息：" + JSON.stringify(options))
  return new Promise<Data<T>>((resolve, reject) => {
    console.log("***********")
    http.createHttp().request(url, options, (err, data) => {
      console.log("err信息：" + JSON.stringify(err.message))
      console.log("返回数据：" + JSON.stringify(data.result))
      if (!err) {
        if (data.responseCode >= 200 && data.responseCode <= 300) {
          console.log((data.result as string))
          resolve(JSON.parse(data.result as string))
        } else if (data.responseCode === 401) {
          AppStorage.Delete("memberStore")
          router.pushUrl({
            url: 'pages/Login'
          })
          reject(data)
        } else {
          promptAction.showToast({
            message: JSON.parse(data.result as string).msg || '请求错误！'
          })
          reject(data)
        }
      } else {
        promptAction.showToast({
          message: '网络错误，稍后再试！'
        })
        reject(err)
      }
    })
  })
}
